package com.domain;

/**
 * @author Charles
 * @date 2023/5/10
 */
public class Account {
    static class BankAccount {
        private int balance = 0;

        public synchronized void deposit(int amount) {
            balance += amount;
        }

        public int getBalance() {
            return balance;
        }
    }

    static class DepositThread implements Runnable {
        private BankAccount account;

        public DepositThread(BankAccount account) {
            this.account = account;
        }

        @Override
        public void run() {
            account.deposit(1);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // 创建一个银行账户对象
        BankAccount account = new BankAccount();

        // 创建100个线程，并让它们向银行账户中存入1元钱
        for (int i = 0; i < 100; i++) {
            Thread thread = new Thread(new DepositThread(account));
            thread.start();
        }
        // 等待所有线程都执行完毕
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 输出银行账户中的余额
        System.out.println("Balance: " + account.getBalance());
    }

}
